package com.oliver.oliveraiagent.controller;
import java.util.HashMap;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.oliver.oliveraiagent.common.BaseResponse;
import com.oliver.oliveraiagent.common.ResultUtils;
import com.oliver.oliveraiagent.model.dto.chatMessage.ChatMessagePageRespone;
import com.oliver.oliveraiagent.model.entity.ChatMessage;
import com.oliver.oliveraiagent.model.entity.User;
import com.oliver.oliveraiagent.service.ChatMessageService;
import com.oliver.oliveraiagent.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName MessageController
 * @Description TODO
 * @Author snow
 * @Date 2025/5/25 19:36
 **/

@RestController
@RequestMapping("/message")
public class ChatMessageController {

    @Resource
    private ChatMessageService chatMessageService;

    @GetMapping("/getPage")
    public BaseResponse<ChatMessagePageRespone> getPage(int current, int size, Integer userId) {
        //  如果没有登录，代表返回空
        ChatMessagePageRespone res = new ChatMessagePageRespone();
        if (userId == null){
            return ResultUtils.success(res);
        }
        //  最多只返回30天前的数据
        Page<ChatMessage> page = chatMessageService.lambdaQuery()
                .eq(ChatMessage::getUserId, userId)
                .apply("create_time >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)")
                .page(new Page<>(current, size));

        List<ChatMessage> chatMessageList = page.getRecords();
        if (CollectionUtil.isNotEmpty(chatMessageList)){
            Map<String, List<ChatMessage>> map =
                    chatMessageList.stream().collect(Collectors.groupingBy(ChatMessage::getConversationId));
            res.setCurrent(page.getCurrent());
            res.setSize(page.getSize());
            res.setTotal(page.getTotal());
            res.setMap(map);
        }
        return ResultUtils.success(res);
    }

}
